package com.project.myproject.Thread;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author Honorable(mabingqian)
 * @description
 * @date 2020/7/27 14:25
 * @update （更新、优化，注明点）
 */
public class CallableFuture implements Callable<Object> {

    private String name;

    public CallableFuture(String name) {
        this.name = name;
    }

    @Override
    public Object call() throws Exception {
        System.out.println(">>> " + name + " 任务启动");
        Thread.sleep(3000);
        long time = new Date().getTime();
        System.out.println(">>> " + name + " 任务终止");
        return name + "任务返回运行结果,当前任务时间【" + time + "毫秒】";
    }
}

class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        int taskSize = 3;
        // 创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);//固定线程数
        List<Future> list = new ArrayList<>();
        for (int i = 0; i < taskSize; i++) {
            Callable c = new CallableFuture(i + " ");
            Future f = pool.submit(c);
            System.out.println("============================ " + f.isDone());
            list.add(f);
        }
        pool.shutdown();
        int i = 0;
        while (true) {
            for (Future f : list) {
                //判断有一个有返回结果了
                if (f.isDone()) {
                    i++;
                    System.out.println(">>>> " + f.get().toString());
                    System.out.println("================= 第" + i + "个完成的");
                }
            }

            if (i == 3) {
                break;
            }
        }
        //todo 执行顺序：父类静态变量，父类静态代码块，子类静态变量，子类静态代码块，父类非静态变量，父类非静态代码块，父类构造函数，子类非静态变量，子类非静态代码块，子类构造函数
    }
}